package com.nexmo.hangman.web.controller;

import com.nexmo.hangman.domain.Game;
import com.nexmo.hangman.domain.dto.GameStatusDto;
import com.nexmo.hangman.domain.dto.GuessResultDto;
import com.nexmo.hangman.domain.dto.UserDto;
import com.nexmo.hangman.service.GameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.*;

@RestController
@RequestMapping(value = "/game", method = RequestMethod.POST)
public class GameController {

    private final GameService gameService;

    private static final String USER_ATTR = "user";
    private static final String GAME_ATTR = "game";

    @Autowired
    public GameController(GameService gameService) {
        this.gameService = gameService;
    }

    @RequestMapping(value = "/start" )
    public GameStatusDto startGame(HttpSession session) {
        UserDto user = (UserDto)session.getAttribute(USER_ATTR);
        GameStatusDto newGame = gameService.generateGame(user.getId());
        addToSession(newGame, session);
        return newGame;
    }

    private void addToSession(GameStatusDto newGame, HttpSession session) {
        session.setAttribute(GAME_ATTR, newGame);
    }

    @RequestMapping(value = "/load", method = RequestMethod.GET)
    public GameStatusDto loadPreviousGame(HttpSession session) {
        UserDto user = (UserDto)session.getAttribute(USER_ATTR);
        GameStatusDto game = gameService.getUnfinishedGame(user.getId());
        addToSession(game, session);
        return game;
    }

    @RequestMapping(value = "/guess")
    public GuessResultDto makeGuess(@RequestParam Character guessChar, HttpSession session ) {
		GameStatusDto game = (GameStatusDto)session.getAttribute(GAME_ATTR);
        GuessResultDto guessResultDto = gameService.guess(guessChar, game.getGameId());
        if ( (guessResultDto.getLost() != null  && guessResultDto.getLost())  ||
            ( guessResultDto.getWon() != null  && guessResultDto.getWon())) {
            session.removeAttribute(GAME_ATTR);
        }
        return guessResultDto;
    }

    //@ExceptionHandler()
}
